package xyz.liut.liutlibraries;

import android.os.Handler;
import android.os.Message;

/**
 * 1小时内倒计时
 *
 * @min 分
 * @sec 秒
 * @status状态 flase表示倒计时结束
 * 调用setMinAndSec可设置初始时间
 * 接收后调用.srart()方法
 * Created by liut_ on 2016/5/4.
 */

public class DaoJsThreadsUtil {

    //参与循环
    private int min, sec;

    //接收到的固定参数
    private int myMin, mySec;

    private OnRunListener listener;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            listener.run(msg.arg1, msg.arg2, (Boolean) msg.obj);
        }
    };
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(999);
                Message msg = handler.obtainMessage();
                msg.arg1 = min;
                msg.arg2 = sec;
                if (min != -1) {
                    msg.obj = true;
                    if (sec == 0) {
                        msg.sendToTarget();
                        sec = 59;
                        min--;
                    } else {
                        msg.sendToTarget();
                        sec--;
                    }
                } else {
                    msg.obj = false;
                    msg.sendToTarget();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };

    private DaoJsThreadsUtil() {
    }

    public DaoJsThreadsUtil(OnRunListener listener, int min, int sec) {
        this.myMin = min;
        this.mySec = sec;
        this.listener = listener;
        resetTime();
    }

    public void resetTime() {
        min = myMin;
        sec = mySec;
    }

    public void start() {
        new Thread(runnable).start();
    }

    public interface OnRunListener {
        void run(int min, int sec, boolean status);
    }

}
